#include <iostream>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

int main()
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("socket failed");
        return -1;
    }
    struct sockaddr_in server;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_family = AF_INET;
    server.sin_port = htons(8085);
    int n = bind(sockfd, (const sockaddr*)&server, sizeof(server));
    if (n < 0)
    {
        perror("bind failed");
        return -1;
    }
    n = listen(sockfd, 5);
    if (n < 0)
    {
        perror("listen failed");
        return -1;
    }
    while (1)
    {
        int newsockfd = accept(sockfd, nullptr, nullptr);
        if (newsockfd < 0)
        {
            perror("accept error");
            continue;
        }
        char buffer[4096];
        n = recv(newsockfd, buffer, 4095, 0);
        if (n <= 0)
        {
            perror("recv failed");
            continue;
        }
        std::string body = "<html><body><h1>Hello World</h1></body></html>";
        std::string rsp = "HTTP/1.1 200 OK\r\n";
        rsp += "Content-Length: " + std::to_string(body.size()) + "\r\n";
        rsp += "Content-Type: text/html\r\n";
        rsp += "\r\n";
        rsp += body;

        n = send(newsockfd, rsp.c_str(), rsp.size(), 0);
        if (n < 0)
        {
            perror("send error");
            close(newsockfd);
        }
    }
}